package com.sskj.phoenixcoin.activity;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.HideUtil;
import com.sskj.lib.util.PictureUtil;
import com.sskj.phoenixcoin.R;
import com.sskj.phoenixcoin.bean.AppBank;
import com.sskj.phoenixcoin.component.DaggerUserDataComponent;
import com.sskj.phoenixcoin.presenter.APpRechargeActivityPresenter;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;


public class APpRechargeActivity extends BaseActivity<APpRechargeActivityPresenter> {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.num_edit)
    EditText numEdit;
    @BindView(R.id.second_ll)
    LinearLayout secondLl;
    @BindView(R.id.withdraw_edit)
    EditText withdrawEdit;
    @BindView(R.id.three_ll)
    LinearLayout threeLl;
    @BindView(R.id.tv_copy)
    TextView tvCopy;
    @BindView(R.id.app_exit_login)
    Button appExitLogin;
    @BindView(R.id.bank_name)
    TextView bankName;
    @BindView(R.id.bank_branch)
    TextView bankBranch;
    @BindView(R.id.bank_account)
    TextView bankAccount;
    @BindView(R.id.img_upload)
    ImageView imgUpload;
    private static final String NAME = "photoUpload.jpg";
    private String uploadUrl;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private double exchangeRate;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_recharge;
    }

    @Override
    public APpRechargeActivityPresenter getPresenter() {
        return new APpRechargeActivityPresenter();
    }

    public static void start(Context context, String exchangeRate) {
        Intent intent = new Intent(context, APpRechargeActivity.class);
        intent.putExtra("exchangeRate", exchangeRate);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        super.initView();
        exchangeRate = Double.valueOf(getIntent().getStringExtra("exchangeRate"));
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        tvTitle.setText("充值");
        rightTv.setVisibility(View.VISIBLE);
        rightTv.setText("充值记录");
        ClickUtil.click(ivBack, () -> {
            finish();
        });
        ClickUtil.click(rightTv, () -> {
            AppRecordActivity.start(this, false);
        });
        ClickUtil.click(imgUpload, () -> {
            selectImage(1);
        });
        ClickUtil.click(appExitLogin, () -> {
            String editNum = numEdit.getText().toString().trim();
            String editMoney = withdrawEdit.getText().toString().trim();
            if (TextUtils.isEmpty(editNum)) {
                ToastUtil.showShort("请输入数量");
                return;
            }
            if (TextUtils.isEmpty(editMoney)) {
                ToastUtil.showShort("请输入金额");
                return;
            }
            if (TextUtils.isEmpty(uploadUrl)) {
                ToastUtil.showShort("请选择转账图片");
                return;
            }
            mPresenter.recharge(editNum, editMoney, String.valueOf(userData.getId()), "1", "1", uploadUrl);
        });
        numEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {     //删除.后面超过两位的数字
//                if (s.toString().contains(".")) {
//                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
//                        s = s.toString().subSequence(0,
//                                s.toString().indexOf(".") + 3);
//                        numEdit.setText(s);
//                        numEdit.setSelection(s.length());
//                    }
//                }
//
//                //如果.在起始位置,则起始位置自动补0
//                if (s.toString().trim().substring(0).equals(".")) {
//                    s = "0" + s;
//                    numEdit.setText(s);
//                    numEdit.setSelection(2);
//                }
//
//                //如果起始位置为0并且第二位跟的不是".",则无法后续输入
//                if (s.toString().startsWith("0")
//                        && s.toString().trim().length() > 1) {
//                    if (!s.toString().substring(1, 2).equals(".")) {
//                        numEdit.setText(s.subSequence(0, 1));
//                        numEdit.setSelection(1);
//                        return;
//                    }
//                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    withdrawEdit.setText(NumberUtil.keepMax2(Double.valueOf(s.toString()) * exchangeRate));
                } else {
                    withdrawEdit.setText("");
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.getOfficialBank();
    }

    private void selectImage(int requestCode) {
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())
                                .previewImage(true)
                                .isCamera(true)
                                .imageFormat(PictureMimeType.JPEG)
                                .maxSelectNum(1)
                                .compress(true)
                                .forResult(requestCode);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            if (selectList != null && selectList.size() > 0) {
                LocalMedia media = selectList.get(0);
                String url;
                if (media.isCompressed()) {
                    url = media.getCompressPath();
                } else {
                    url = media.getPath();
                }
                Glide.with(this).load(url).into(imgUpload);
                mPresenter.submitVerify(new File(url));
            }
        }

    }

    private void setFilePath(Bitmap smallBitmap, String filePath, File file) {
        imgUpload.setBackground(new BitmapDrawable(smallBitmap));
    }


    public void upload(boolean upload, String url) {
        if (upload) {
            uploadUrl = url;
        } else {
            imgUpload.setBackgroundResource(R.mipmap.app_img_copy);
        }
    }

    //充值成功
    public void successUi() {
        AppRecordActivity.start(this, false);
    }

    // 获取官方bank
    public void successBank(AppBank appBank) {
        bankName.setText("开户名:  " + appBank.getName());
        bankAccount.setText("开户账号:  " + appBank.getBankCardNo());
        bankBranch.setText("开户行:  " + appBank.getBankCardType() + appBank.getBankCardOpenBank());
    }
}
